/**
 * @author: thon.ju
 * @date: 2013/10/22
 * @description: compress js and css
 */

var fs = require('fs');
var uglify = require('./uglify');
var yuicompressor = require('yuicompressor');

module.exports = function($CONFIG) {

	var comment = "";
	fs.readFile('package.json', 'utf-8', function(err, data) {
		var info = JSON.parse(data);
		
		// 添加打包注释
		comment = '\/\*\*\n\* ' + info.name
		+'\n\* ' + info.description
		+'\n\* Version ' + info.version
		+'\n\* Builded by ' + info.author.name +' at '+ new Date()
		+'\n\*\/\n';
	});
	
	var i = 0, len = $CONFIG.fileList.length;
	for (; i < len; i++) {
		(function(i) {
			if ($CONFIG.fileList[i].ftype === 'js') {
				fs.readFile($CONFIG.basePath + $CONFIG.fileList[i].fpath,'utf-8', function(err, data) {
							if (err) {
								console.log(err);
								return;
							}
							fs.writeFile($CONFIG.basePath + $CONFIG.fileList[i].output, comment + uglify(data), 'utf-8', function(err) {
								if (err) {
									console.log(err);
									return;
								}
							});
						});
			} else if ($CONFIG.fileList[i].ftype === 'css') {
				yuicompressor.compress($CONFIG.basePath + $CONFIG.fileList[i].fpath,
					{
						charset : 'utf8',
						type : $CONFIG.fileList[i].ftype,
						nomunge : false,
						'line-break' : 80
					},
					function(err, data, extra) {
						data = comment + data;
						data = data.replace(/(.png|.jpg|.gif)/g, '$1?v=' + (new Date().getTime()));
						fs.writeFile($CONFIG.basePath + $CONFIG.fileList[i].output, data,'utf-8', function(err) {
							if (err) {
								console.log('err:', err);
							}
						});
					});
			}
		})(i);
	}
};
